<template>
  <div class="main">
    <el-table :data="list" v-loading="loading" row-key="key">
      <el-table-column
        type="index"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column v-if="sales.length" label="属性组合" align="center">
        <el-table-column v-for="(sale, index) in sales" :key="index" :label="sale.attrName"
                         :prop="'attr_' + index"
                         align="center"
        />
      </el-table-column>
      <el-table-column label="商品名称" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.skuName" style="width: 100%"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="标题">
        <template slot-scope="scope">
          <el-input v-model="scope.row.skuTitle" style="width: 100%"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="副标题">
        <template slot-scope="scope">
          <el-input v-model="scope.row.skuSubtitle" style="width: 100%"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="价格￥" align="center">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.price" controls-position="right" :precision="2" :min="0"
                           style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="expand">
            <div>
              <p style="display: inline">选择图集，或者</p>
              <simple-image-upload style="display: inline-block; margin-left: 5px"
                                   @uploadSuccess="uploadSuccess($event, props.row)"
              >
                <el-button icon="el-icon-upload" size="mini" type="primary">继续上传</el-button>
              </simple-image-upload>
            </div>

            <div style="display: flex; flex-wrap: wrap; justify-content: left; margin-top: 20px">
              <el-card v-for="(item, index) in props.row.images" :body-style="{ padding: '0px' }"
                       style="height: 230px; margin: 0 10px 20px 10px"
              >

                <image-preview :src="item.url" :width="'170px'" :height="'170px'"/>

                <div style="padding: 10px; display: flex; justify-content: space-between;">
                  <el-checkbox size="mini" v-model="item.selected" :true-label="1" :false-label="0"
                               style="margin-top: 5px"
                  ></el-checkbox>
                  <el-checkbox border size="mini" @change="imgDefaultChange($event, props.row.images, item, index)"
                               v-model="item.defaultImg" :true-label="1" :false-label="0"
                  >设为默认
                  </el-checkbox>
                </div>
              </el-card>
            </div>

            <el-form :model="props.row" label-width="120px" style="margin-top: 10px">
              <el-form-item label="设置折扣">
                满
                <el-input-number
                  v-model="props.row.fullCount"
                  controls-position="right"
                  :precision="2"
                  :min="0"
                  style="margin: 0 10px"
                />
                件 打
                <el-input-number
                  v-model="props.row.discount"
                  controls-position="right"
                  :precision="2"
                  :min="0"
                  style="margin: 0 10px"
                />
                折
                <el-checkbox v-model="props.row.discountAppend" :true-label="1" :false-label="0"
                             style="margin-left: 20px"
                >可叠加优惠
                </el-checkbox>
              </el-form-item>

              <el-form-item label="设置满减">
                满
                <el-input-number
                  v-model="props.row.fullPrice"
                  controls-position="right"
                  :precision="2"
                  :min="0"
                  style="margin: 0 10px"
                />
                元 减
                <el-input-number
                  v-model="props.row.reducePrice"
                  controls-position="right"
                  :precision="2"
                  :min="0"
                  style="margin: 0 10px"
                />
                元
                <el-checkbox v-model="props.row.fullAppend" :true-label="1" :false-label="0" style="margin-left: 20px">
                  可叠加优惠
                </el-checkbox>
              </el-form-item>

              <el-form-item label="商品描述" prop="skuDesc">
                <el-input v-model="props.row.skuDesc" type="textarea" placeholder="请输入内容"/>
              </el-form-item>

              <el-form-item label="设置会员价">
                <div v-for="item in rowMemberList[props.row.key]" :key="item.id" style="margin-bottom: 15px">
                  {{ item.name }}
                  <el-input-number
                    v-model="item.price"
                    controls-position="right"
                    :precision="2"
                    :min="0"
                    style="margin: 0 10px"
                  />
                </div>
                <i v-if="!rowMemberList.length" class="el-icon-loading"></i>
              </el-form-item>
            </el-form>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { rememberEqual } from '@/utils/my/arrayUtil'
import { generateCartesian } from '@/utils/my/Cartesian'

export default {
  name: 'pubSku',
  data() {
    return {
      loading: false,
      sales: [],
      list: [],
      // 所有行数据的会员列表
      rowMemberList: [],
      // 页面缓存
      remember: undefined
    }
  },
  methods: {
    init(sales = [], baseForm) {

      if (sales.length) {
        // 比较属性是否改动过了，如果改动过需要重新计算
        if (!rememberEqual(this.remember, sales, baseForm)) {
          // 表头
          this.sales = sales

          // 生成表格数据
          this.createTableList(sales, baseForm)
        }
      } else {
        this.sales = []
        this.list = []
      }

    },
    // 生成表格数据
    createTableList(sales, baseForm) {
      this.list = []
      this.loading = true

      /*

          [
             [{attrId: 1, attrName: '黑色'},{attrId: 2, attrName: '128GB'}]
             [{attrId: 1, attrName: '黑色'},{attrId: 2, attrName: '256GB'}]
             [{attrId: 1, attrName: '白色'},{attrId: 2, attrName: '128GB'}]
             [{attrId: 1, attrName: '白色'},{attrId: 2, attrName: '256GB'}]
          ]

       */
      const cartesian = generateCartesian(sales)

      for (let i = 0; i < cartesian.length; i++) {
        const row = {
          // 唯一标识 否则 table column 使用 expand 类型时，需要点击两次才会打开
          key: i,
          skuName: baseForm.spuName,
          skuTitle: baseForm.title,
          skuSubtitle: baseForm.subTitle,
          price: 0,
          // 图集
          images: this.createImgObjs(baseForm),
          skuDesc: undefined,
          // 折扣
          fullCount: undefined,
          discount: undefined,
          discountAppend: 0,
          //  满减
          fullPrice: undefined,
          reducePrice: undefined,
          fullAppend: 0
        }

        // [{attrId: 1, attrName: '黑色'},{attrId: 2, attrName: '128GB'}]
        const rowAttrs = cartesian[i]

        for (let i = 0; i < rowAttrs.length; i++) {
          // 动态生成属性
          row['attr_' + i] = rowAttrs[i].attrName
        }

        row.sales = rowAttrs

        this.list.push(row)
      }

      this.getMemberList()

      this.remember = {
        sales: sales,
        // 浅拷贝，如果源对象的属性值是基本数据类型（如字符串、数字、布尔值等），那么它会直接复制该属性值
        // 如果源对象的属性值是引用类型（如对象、数组等），那么只会复制它们的引用而不是复制其内容
        form: Object.assign({}, baseForm)
      }

      this.loading = false
    },
    // 创建图片对象
    createImgObjs(baseForm) {
      let imgs = baseForm.imgs
      const imgObjs = []
      if (imgs) {
        imgs.forEach((item, i) => {
          imgObjs[i] = {
            url: item,
            selected: 1,
            defaultImg: 0
          }
        })
      }
      return imgObjs
    },
    /**
     * 获取会员信息
     */
    getMemberList() {
      this.rowMemberList = []
      if (this.list.length) {
        // 查找有价格特权的会员
        this.$api.get('/member/memberLevel/filter', { 'priviledgeMemberPrice': 1 }).then(({ data }) => {
          for (let i = 0; i < this.list.length; i++) {
            const mbs = []
            for (let j = 0; j < data.length; j++) {
              mbs.push({
                id: data[j].id,
                name: data[j].name,
                price: undefined
              })
            }
            this.rowMemberList.push(mbs)
          }
        })
      }
    },
    /**
     * 默认图片 check box 改变事件
     * @param value 组件更新后的值
     * @param images 该列的所有图片数组
     * @param item 操作项
     * @param index 操作项下标
     */
    imgDefaultChange(value, images, item, index) {
      if (value === 1) {
        item.selected = 1
        images.forEach(img => {
          if (img.url !== item.url) {
            img.defaultImg = 0
          }
        })
      }
    },
    /**
     * 文件上传成功
     * @param url 地址
     * @param row 行对象
     */
    uploadSuccess(url, row) {
      row.images.push({
        url: url,
        selected: 1,
        defaultImg: 0
      })
    },
    // 获取要提交的值
    getForm() {
      // 提取选择的图片
      this.list.forEach((item, i) => {
        item.selectedImages = item.images.filter(img => img.selected === 1)
        // 过滤会员价格
        if (this.rowMemberList[i]) {
          item.memberPrice = this.rowMemberList[i].filter(i => i.price)
        }
      })
      return this.list
    },
    // 表单校验
    validate() {
      let msg = undefined
      for (let i = 0; i < this.getForm().length; i++) {
        let row = this.getForm()[i]
        let no = i + 1
        if (!row.skuName) {
          msg = '商品名称不能为空，行：' + no
          break
        }
        if (!row.skuTitle) {
          msg = '标题不能为空，行：' + no
          break
        }
        // if (!row.skuSubtitle) {
        //   msg = '副标题不能为空，行：' + no
        //   break
        // }
        if (row.price === undefined) {
          msg = '价格不能为空，行：' + no
          break
        }
        if (!row.selectedImages.length) {
          msg = '至少选择一张图集，行：' + no
          break
        }
      }
      return msg
    }
  }
}
</script>

<style scoped>
.main {
  margin: 30px 0px 0 0px;
}

.expand {
  background: #FAFAFA;
  padding: 20px;
  margin: 15px 20px;
  border-radius: 5px;
}
</style>
